<?php
namespace app\model;

use app\common\model\_Base;

class Admin extends _Base
{
    /**
     * 设置关联模型Role
     */
    public function role()
    {
        return $this->belongsTo('Role');
    }

    /**
     * 设置获取器 获取最后登录时间时更改时间格式
     * @param string $value 传入值
     */
    public function getLastLoginTimeAttr($value)
    {   
        return $this->getTime($value);
    }

    /**
     * 保存数据
     * @param  obj $data 数据
     * @param  integer  $id 数据编号
     * @return bool       
     */
    public static function doSave($data,$id = '')
    {   
        $user = $id?Admin::get($id):new Admin;
        !empty($data['name']) && $user['name'] = $data['name'];
        !empty($data['password']) && $user->password = md5($data['password']);
        !empty($data['role_id']) && $user->role_id = $data['role_id'];
        isset($data['status']) && strlen($data['status'])>0 && $user->status = $data['status'];
        $user->save();
        return;
    }

    /**
     * 删除数据 软删除 二次真实删除
     * @param  integer $id 数据编号
     * @return bool       
     */
    public static function doDelete($id)
    {
        $user = Admin::get($id);
        $user->status = self::STATUS_DELETED;
        $user->save();
        return false;
    }

    /**
     * 根据id或name获取用户详情
     * @param  integer    编号
     * @return array
     */
    public static function doDetail($id = '', $name = '')
    {   
        $id && $cond = ['id'=>$id];
        $name && $cond = ['name'=>$name];
        $user = Admin::with(['role'])->where($cond)->find()->hidden(['password'])->append(['status_text']);
        $role = $user->role['name'];
        unset($user->role);
        $user['role'] = $role;
        return $user;
    }

    /**
     * 获取数据
     * @param  array    $cond  条件
     * @param  string   $alias 条件表别名
     * @param  integer  $page  页码
     * @param  integer  $size 每页条数
     * @return array
     */
    public static function doList($cond = [], $alias = false, $page = 1, $size = 10, $order = 'id desc')
    {   
        $total = Admin::where($cond)->count();
        $list = Admin::where($cond)->with('role')->page($page,$size)->order($order)->select();
        if(!$list->isEmpty()){
            $list->hidden(['password']) 
                ->append(['status_text']);
            foreach ($list as &$value) {
                $role = $value->role['name'];
                unset($value->role);
                $value['role'] = $role;
            }
        }
        return ['total' => $total,'list'=> $list];
    }

}